<template>
  <div class="album-container">
    <!-- 头部操作栏 -->
<<<<<<< HEAD
    <div class="page-header">
      <div class="header-left">
        <h2 class="header-title">
          <el-icon><FolderOpened /></el-icon>
          {{ currentAlbum ? currentAlbum.name : "我的相册" }}
        </h2>
        <el-button
          v-if="currentAlbum"
          class="back-btn"
          @click="currentAlbum = null"
          :icon="ArrowLeft"
        >
          返回相册列表
        </el-button>
      </div>

      <!-- 搜索与操作区 -->
      <div class="header-actions">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索相册名称或描述..."
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon class="search-icon"><Search /></el-icon>
          </template>
        </el-input>

        <el-button type="primary" class="create-btn" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建相册
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 相册列表 -->
      <div v-if="!currentAlbum" class="album-grid" v-loading="loading">
        <el-empty
          v-if="!loading && filteredAlbums.length === 0"
          description="暂无相册，点击右上角创建"
          class="empty-state"
        />

        <div
          v-for="album in filteredAlbums"
          :key="album.id"
          class="album-card"
          @click="openAlbum(album)"
        >
          <!-- 封面区域 -->
          <div class="cover-wrapper">
            <img
              :src="album.cover || defaultCover"
              class="album-cover"
              alt="相册封面"
            />
            <div class="photo-count">
              <el-icon><Picture /></el-icon>
              {{ album.photos.length }}
            </div>
            <div class="privacy-tag" :class="{ private: album.isPrivate }">
              {{ album.isPrivate ? "私有" : "公开" }}
            </div>
          </div>

          <!-- 相册信息 -->
          <div class="album-info">
            <h3 class="album-title">{{ album.name }}</h3>
            <p class="album-desc">{{ album.description || "暂无描述" }}</p>
            <div class="meta-info">
              <span class="create-time">
                <el-icon><Clock /></el-icon>
                {{ formatDate(album.createTime) }}
              </span>
              <el-dropdown @click.stop>
                <el-icon class="more-btn"><More /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="editAlbum(album)">
                      编辑信息
                    </el-dropdown-item>
                    <el-dropdown-item @click="addImagesToAlbum(album)">
                      添加图片
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteAlbum(album.id)">
                      删除相册
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 相册详情 -->
      <div v-else class="album-detail" v-loading="detailLoading">
        <div class="detail-info">
          <p class="album-desc">{{ currentAlbum.description || "暂无描述" }}</p>
          <div class="album-meta">
            <span class="photo-count">
              <el-icon><Picture /></el-icon>
              {{ currentAlbum.photos.length }} 张图片
            </span>
            <span class="create-time">
              <el-icon><Clock /></el-icon>
              {{ formatDate(currentAlbum.createTime) }}
            </span>
          </div>
          <div class="detail-actions">
            <el-button type="primary" @click="addImagesToAlbum(currentAlbum)">
              <el-icon><Plus /></el-icon>
              添加图片
            </el-button>
          </div>
        </div>

        <!-- 图片网格 -->
        <div class="photo-grid">
          <el-empty
            v-if="
              !detailLoading &&
              (!currentAlbum.photos || currentAlbum.photos.length === 0)
            "
            description="暂无图片，点击右上角添加"
          />

          <div
            v-for="photo in currentAlbum.photos"
            :key="photo.id"
            class="photo-item"
            @click="previewImage(photo)"
          >
            <el-image
              :src="getFullImageUrl(photo.file_path)"
              fit="cover"
              loading="lazy"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
            <div class="photo-info">
              <span class="photo-name">{{ photo.file_name }}</span>
              <div class="photo-tags">
                <el-tag
                  v-for="tag in JSON.parse(photo.tags)"
                  :key="tag"
                  size="small"
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
=======
    <el-header class="album-header">
      <div class="header-content">
        <h2 class="header-title">
          <el-icon><FolderOpened /></el-icon>
          我的相册
        </h2>

        <!-- 搜索与操作区 -->
        <div class="header-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索相册名称或描述..."
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>

          <el-button
            type="primary"
            class="create-btn"
            @click="showCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            新建相册
          </el-button>
        </div>
      </div>
    </el-header>

    <!-- 相册列表 -->
    <el-main class="album-main">
      <el-empty
        v-if="!loading && filteredAlbums.length === 0"
        description="暂无相册，点击右上角创建"
        class="empty-state"
      />

      <el-row v-loading="loading" :gutter="20" class="album-grid">
        <el-col
          v-for="album in filteredAlbums"
          :key="album.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
        >
          <el-card
            class="album-card"
            shadow="hover"
            @click="openAlbum(album.id)"
          >
            <!-- 封面区域 -->
            <div class="cover-wrapper">
              <img
                :src="album.cover || defaultCover"
                class="album-cover"
                alt="相册封面"
              />
              <div class="photo-count">
                <el-icon><Picture /></el-icon>
                {{ album.photos.length }}
              </div>
              <div class="privacy-tag" :class="{ private: album.isPrivate }">
                {{ album.isPrivate ? "私有" : "公开" }}
              </div>
            </div>

            <!-- 相册信息 -->
            <div class="album-info">
              <h3 class="album-title">{{ album.name }}</h3>
              <p class="album-desc">{{ album.description || "暂无描述" }}</p>
              <div class="meta-info">
                <span class="create-time">
                  <el-icon><Clock /></el-icon>
                  {{ formatDate(album.createTime) }}
                </span>
                <el-dropdown @click.stop>
                  <el-icon class="more-btn"><More /></el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="editAlbum(album)">
                        编辑信息
                      </el-dropdown-item>
                      <el-dropdown-item @click="deleteAlbum(album.id)">
                        删除相册
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331

    <!-- 新建相册弹窗 -->
    <AlbumCreateDialog
      v-model:visible="showCreate"
      :edit-data="currentEditAlbum"
      @created="handleAlbumCreated"
      @updated="handleAlbumUpdated"
    />
<<<<<<< HEAD

    <!-- 添加图片对话框 -->
    <AlbumImageDialog
      v-if="currentAlbumId"
      v-model:visible="showAddImages"
      :album-id="currentAlbumId"
      @added="handleImagesAdded"
    />

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="previewUrls"
      :initial-index="currentPreviewIndex"
      @close="showViewer = false"
    />
=======
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { format } from "date-fns";
import {
  FolderOpened,
  Search,
  Plus,
  Picture,
  Clock,
  More,
<<<<<<< HEAD
  ArrowLeft,
} from "@element-plus/icons-vue";
import AlbumCreateDialog from "../components/AlbumCreateDialog.vue";
import AlbumImageDialog from "../components/AlbumImageDialog.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

interface Photo {
  id: number;
  file_name: string;
  file_path: string;
  tags: string;
}

=======
} from "@element-plus/icons-vue";
import AlbumCreateDialog from "../components/AlbumCreateDialog.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
interface Album {
  id: number;
  name: string;
  description?: string;
  cover?: string;
  isPrivate: boolean;
  createTime: string;
<<<<<<< HEAD
  photos: Photo[];
=======
  photos: string[];
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
}

// 响应式状态
const searchKeyword = ref("");
const showCreate = ref(false);
const albums = ref<Album[]>([]);
const loading = ref(false);
const currentEditAlbum = ref<Album | null>(null);
<<<<<<< HEAD
const showAddImages = ref(false);
const currentAlbumId = ref<number | null>(null);
const currentAlbum = ref<Album | null>(null);
const detailLoading = ref(false);
const showViewer = ref(false);
const previewUrls = ref<string[]>([]);
const currentPreviewIndex = ref(0);
=======
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331

// 获取相册列表
const fetchAlbums = async () => {
  loading.value = true;
  try {
    const response = await axios.get("http://localhost:3000/albums", {
<<<<<<< HEAD
      params: { userId: 1 },
=======
      params: { userId: 1 }, // 这里可以根据实际登录用户ID来设置
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
    });
    albums.value = response.data.map((album: any) => ({
      ...album,
      createTime: album.created_at,
<<<<<<< HEAD
      photos: [],
=======
      photos: [], // 暂时为空数组，后续可以添加获取相册图片的功能
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
    }));
  } catch (error) {
    console.error("获取相册列表失败:", error);
    ElMessage.error("获取相册列表失败");
  } finally {
    loading.value = false;
  }
};

<<<<<<< HEAD
// 获取相册详情
const fetchAlbumDetail = async (albumId: number) => {
  detailLoading.value = true;
  try {
    const response = await axios.get(
      `http://localhost:3000/albums/${albumId}/images`
    );
    const albumResponse = await axios.get(
      `http://localhost:3000/albums/${albumId}`
    );

    currentAlbum.value = {
      ...albumResponse.data,
      photos: response.data,
    };
  } catch (error) {
    console.error("获取相册详情失败:", error);
    ElMessage.error("获取相册详情失败");
  } finally {
    detailLoading.value = false;
  }
};

=======
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
// 在组件挂载时获取相册列表
onMounted(() => {
  fetchAlbums();
});

const defaultCover = "https://placehold.co/300x200?text=暂无封面";

// 计算属性
const filteredAlbums = computed(() => {
  const keyword = searchKeyword.value.toLowerCase();
  return albums.value.filter(
    (album) =>
      album.name.toLowerCase().includes(keyword) ||
      album.description?.toLowerCase().includes(keyword)
  );
});

// 搜索处理
const handleSearch = () => {
<<<<<<< HEAD
=======
  // 可以添加防抖处理
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
  console.log("搜索关键词:", searchKeyword.value);
};

// 方法
const formatDate = (dateStr: string) => {
  return format(new Date(dateStr), "yyyy-MM-dd HH:mm");
};

<<<<<<< HEAD
const openAlbum = (album: Album) => {
  currentAlbum.value = album;
  fetchAlbumDetail(album.id);
=======
const openAlbum = (id: number) => {
  console.log("打开相册:", id);
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
};

// 显示创建对话框
const showCreateDialog = () => {
  currentEditAlbum.value = null;
  showCreate.value = true;
};

// 处理相册创建
const handleAlbumCreated = (newAlbum: any) => {
  albums.value.unshift({
    ...newAlbum,
    createTime: new Date().toISOString(),
    photos: [],
  });
  ElMessage.success("相册创建成功");
};

// 处理相册更新
const handleAlbumUpdated = (updatedAlbum: any) => {
  const index = albums.value.findIndex((a) => a.id === updatedAlbum.id);
  if (index !== -1) {
    albums.value[index] = {
      ...albums.value[index],
      ...updatedAlbum,
<<<<<<< HEAD
      createTime: albums.value[index].createTime,
    };
    if (currentAlbum.value?.id === updatedAlbum.id) {
      currentAlbum.value = {
        ...currentAlbum.value,
        ...updatedAlbum,
      };
    }
=======
      createTime: albums.value[index].createTime, // 保持原有的创建时间
    };
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
  }
  ElMessage.success("相册更新成功");
};

// 编辑相册
const editAlbum = (album: Album) => {
  currentEditAlbum.value = album;
  showCreate.value = true;
};

// 删除相册
const deleteAlbum = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这个相册吗？删除后将无法恢复。",
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    await axios.delete(`http://localhost:3000/albums/${id}`, {
<<<<<<< HEAD
      params: { userId: 1 },
    });
    albums.value = albums.value.filter((a) => a.id !== id);
    if (currentAlbum.value?.id === id) {
      currentAlbum.value = null;
    }
=======
      params: { userId: 1 }, // 这里可以根据实际登录用户ID来设置
    });
    albums.value = albums.value.filter((a) => a.id !== id);
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
    ElMessage.success("相册删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除相册失败:", error);
      ElMessage.error("删除相册失败");
    }
  }
};
<<<<<<< HEAD

// 添加图片到相册
const addImagesToAlbum = (album: Album) => {
  currentAlbumId.value = album.id;
  showAddImages.value = true;
};

// 处理图片添加成功
const handleImagesAdded = () => {
  if (currentAlbum.value) {
    fetchAlbumDetail(currentAlbum.value.id);
  }
};

// 获取完整的图片URL
const getFullImageUrl = (path: string) => {
  return `http://localhost:3000/${path}`;
};

// 预览图片
const previewImage = (photo: Photo) => {
  if (!currentAlbum.value?.photos) return;

  previewUrls.value = currentAlbum.value.photos.map((p) =>
    getFullImageUrl(p.file_path)
  );
  currentPreviewIndex.value = currentAlbum.value.photos.findIndex(
    (p) => p.id === photo.id
  );
  showViewer.value = true;
};
=======
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
</script>

<style scoped lang="scss">
@import "../style/common.scss";
<<<<<<< HEAD

.album-container {
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-header {
  padding: 20px;
  background: white;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
=======
.album-container {
  height: 100%;
  background: #f5f7fa;
  padding: 20px;
}

.album-header {
  height: auto !important;
  padding: 0;
  margin-bottom: 24px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  }

  .header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 0;
    font-size: 20px;
    color: #303133;

    .el-icon {
      font-size: 24px;
      color: #409eff;
    }
  }

  .header-actions {
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
    display: flex;
    align-items: center;
    gap: 16px;

<<<<<<< HEAD
    .header-title {
      display: flex;
      align-items: center;
      gap: 8px;
      margin: 0;
      font-size: 20px;
      color: #303133;

      .el-icon {
        font-size: 24px;
        color: #409eff;
      }
    }

    .back-btn {
      margin-left: 8px;
    }
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 16px;

    .search-input {
      width: 280px;
=======
    .search-input {
      width: 280px;
      transition: all 0.3s;

      &:focus-within {
        width: 320px;
      }
    }

    .create-btn {
      padding: 8px 16px;
      border-radius: 6px;
    }
  }
}

.album-main {
  padding: 0;
  margin-top: 16px;

  .empty-state {
    padding: 40px 0;
    background: white;
    border-radius: 8px;
  }
}

.album-grid {
  padding: 8px;
}

.album-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-4px);
  }

  .cover-wrapper {
    position: relative;
    border-radius: 6px;
    overflow: hidden;
    height: 200px;

    .album-cover {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .photo-count {
      position: absolute;
      bottom: 12px;
      left: 12px;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      padding: 4px 12px;
      border-radius: 20px;
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
    }

    .privacy-tag {
      position: absolute;
      top: 12px;
      right: 12px;
      padding: 4px 10px;
      border-radius: 12px;
      background: rgba(255, 255, 255, 0.9);
      font-size: 12px;

      &.private {
        background: rgba(245, 108, 108, 0.9);
        color: white;
      }
    }
  }

  .album-info {
    padding: 16px 0 8px;

    .album-title {
      margin: 0 0 8px;
      font-size: 16px;
      color: #303133;
      @include text-ellipsis;
    }

    .album-desc {
      margin: 0 0 12px;
      font-size: 13px;
      color: #606266;
      line-height: 1.4;
      @include text-ellipsis(2);
    }

    .meta-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #909399;
      font-size: 12px;

      .create-time {
        display: flex;
        align-items: center;
        gap: 4px;
      }

      .more-btn {
        padding: 4px;
        transition: all 0.3s;

        &:hover {
          color: #409eff;
          transform: rotate(90deg);
        }
      }
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
    }
  }
}

<<<<<<< HEAD
.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.album-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 8px;
}

.album-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  .cover-wrapper {
    position: relative;
    height: 200px;

    .album-cover {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .photo-count {
      position: absolute;
      bottom: 12px;
      left: 12px;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      padding: 4px 12px;
      border-radius: 20px;
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
    }

    .privacy-tag {
      position: absolute;
      top: 12px;
      right: 12px;
      padding: 4px 10px;
      border-radius: 12px;
      background: rgba(255, 255, 255, 0.9);
      font-size: 12px;

      &.private {
        background: rgba(245, 108, 108, 0.9);
        color: white;
      }
    }
  }

  .album-info {
    padding: 16px;

    .album-title {
      margin: 0 0 8px;
      font-size: 16px;
      color: #303133;
      @include text-ellipsis;
    }

    .album-desc {
      margin: 0 0 12px;
      font-size: 13px;
      color: #606266;
      line-height: 1.4;
      @include text-ellipsis-multiple(2);
    }

    .meta-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      color: #909399;
      font-size: 12px;

      .create-time {
        display: flex;
        align-items: center;
        gap: 4px;
      }

      .more-btn {
        padding: 4px;
        transition: all 0.3s;

        &:hover {
          color: #409eff;
          transform: rotate(90deg);
        }
      }
    }
  }
}

.album-detail {
  .detail-info {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;

    .album-desc {
      margin: 0 0 16px;
      color: #606266;
      font-size: 14px;
    }

    .album-meta {
      display: flex;
      gap: 16px;
      color: #909399;
      font-size: 14px;
      margin-bottom: 16px;

      span {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    .detail-actions {
      display: flex;
      justify-content: flex-end;
    }
  }
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.photo-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  }

  .el-image {
    width: 100%;
    height: 200px;
  }

  .photo-info {
    padding: 12px;

    .photo-name {
      display: block;
      font-size: 14px;
      color: #303133;
      margin-bottom: 8px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .photo-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 4px;

      .tag {
        font-size: 12px;
      }
    }
  }
}

.image-error {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;

  .el-icon {
    font-size: 24px;
    margin-bottom: 8px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;

    .header-left {
      width: 100%;
      justify-content: space-between;
    }

    .header-actions {
      width: 100%;
      flex-direction: column;

      .search-input {
        width: 100%;
      }

      .create-btn {
        width: 100%;
      }
    }
  }

  .album-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }

  .photo-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
}
=======
@media (max-width: 768px) {
  .album-header {
    .header-content {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;
    }

    .header-actions {
      flex-direction: column;

      .search-input {
        width: 100% !important;
      }
    }
  }

  .album-card {
    margin-bottom: 16px;
  }
}
>>>>>>> 808097149b9b03668259b819c5529eb708b7a331
</style>
